<template>
  <div>
    <el-card class="top-operation-card" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="班组名称" prop="workTeamName">
          <el-input
            v-model="queryParams.workTeamName"
            placeholder="请输入班组名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="plan-table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['task:team:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="plain"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['task:team:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="plain"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['task:team:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="plain"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['task:team:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="teamList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="left" />
        <el-table-column type="index" label="序号" width="60" align="left" />
        <el-table-column label="班组名称" align="left" prop="workTeamName" />
        <el-table-column label="所属部门单位" align="left" prop="deptName" />

        <el-table-column label="备注" align="left" prop="remark" />
        <el-table-column
          label="操作"
          align="left"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['task:team:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['task:team:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改作业班组对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="1220px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-row :gutter="32">
          <el-col :span="12">
            <el-form-item
              label="班组名称"
              prop="workTeamName"
              :rules="{
                required: true,
                message: '必填',
                trigger: 'blur',
              }"
            >
              <el-input
                v-model="form.workTeamName"
                placeholder="请输入班组名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="所属单位" prop="companyId">
              <el-select
                v-model="form.companyId"
                placeholder="请选择所属单位"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in companyOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item> -->
          </el-col>
        </el-row>
        <div class="sub-title" style="padding-left: 17px; margin-bottom: 15px">
          上下班时间
          <el-button
            icon="el-icon-plus"
            type="primary"
            round
            plain
            size="mini"
            style="margin-left: 10px"
            @click="addTeamSpan"
            >新增时间段</el-button
          >
        </div>
        <el-row v-for="(item, index) in form.teamSpanList" :key="index">
          <el-col :span="5">
            <el-form-item
              label="考勤段名称"
              :rules="{
                required: true,
                message: '必填',
                trigger: 'blur',
              }"
              :prop="'teamSpanList.' + index + '.teamSpanName'"
            >
              <el-input
                v-model="item.teamSpanName"
                placeholder="请输入考勤段名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="工作时间"
              :rules="{
                required: true,
                message: '必选',
                trigger: 'change',
              }"
              :prop="'teamSpanList.' + index + '.workTime'"
            >
              <el-time-picker
                is-range
                v-model="item.workTime"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 280px"
              >
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              label="作业区域"
              :rules="{
                required: true,
                message: '必选',
                trigger: 'change',
              }"
              :prop="'teamSpanList.' + index + '.fenceId'"
            >
              <el-select
                v-model="item.fenceId"
                placeholder="请选择所属作业区域"
                style="width: 190px"
              >
                <el-option
                  v-for="fence in fenceOptions"
                  :key="fence.fenceId"
                  :label="fence.fenceName"
                  :value="parseInt(fence.fenceId)"
                >
                  <span style="float: left">{{ fence.fenceName }}</span>

                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ fence.checkName }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="司机"
              :rules="{
                required: true,
                message: '必选',
                trigger: 'change',
              }"
              :prop="'teamSpanList.' + index + '.personId'"
            >
              <el-select
                v-model="item.personId"
                placeholder="请选择司机"
                style="width: 100px"
              >
                <el-option
                  v-for="driver in driverOptions"
                  :key="driver.personId"
                  :label="driver.personName"
                  :value="parseInt(driver.personId)"
                />
              </el-select>
              <el-button
                v-if="index != 0"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="deleteTeamSpan(index)"
                style="margin-left: 15px"
                >删除</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTeam,
  getTeam,
  delTeam,
  addTeam,
  updateTeam,
  exportTeam,
} from "@/api/task/team";
import { getPersonCombo } from "@/api/base/person";
import { getFenceCombo } from "@/api/base/fence";

export default {
  name: "Team",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作业班组表格数据
      teamList: [],
      driverOptions: [],
      fenceOptions: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workTeamName: null,
        workTeamType: "car",
      },
      // 表单参数
      form: {},
    };
  },
  computed: {
    deptId() {
      return this.$store.getters.choosedDeptId;
    },
  },
  watch: {
    deptId: function () {
      this.queryParams.deptId = this.deptId;
      this.getList();
    },
  },
  created() {
    this.getList();
    this.getDriverCombo();
    this.getFenceSelect();
  },
  methods: {
    /** 查询围栏下拉树结构 */
    getFenceSelect() {
      getFenceCombo({ checkPoints: true, deptId: this.deptId }).then(
        (response) => {
          this.fenceOptions = response.data;
        }
      );
    },
    /** 查询司机combo */
    getDriverCombo() {
      getPersonCombo({ personType: "driver", deptId: this.deptId }).then(
        (response) => {
          this.driverOptions = response.data;
        }
      );
    },
    /** 查询作业班组列表 */
    getList() {
      this.loading = true;
      this.queryParams.deptId = this.deptId;

      listTeam(this.queryParams).then((response) => {
        this.teamList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workTeamId: null,
        workTeamName: null,
        teamSpanList: [
          { teamSpanName: null, workTime: null, personId: null, fenceId: null },
        ],
        workTeamType: "car",
        remark: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
        deptId: this.deptId,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.workTeamId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDriverCombo();
      this.getFenceSelect();

      this.open = true;
      this.title = "添加作业班组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const workTeamId = row.workTeamId || this.ids;
      getTeam(workTeamId).then((response) => {
        this.form = response.data;
        if (this.form.teamSpanList.length > 0) {
          this.form.teamSpanList.forEach((v) => {
            v.workTime = [v.startSpan, v.endSpan];
          });
        }
        this.open = true;
        this.title = "修改作业班组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form));
          params.teamSpanList.forEach((v) => {
            v.startSpan = v.workTime[0];
            v.endSpan = v.workTime[1];
          });

          if (this.form.workTeamId != null) {
            updateTeam(params).then((response) => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addTeam(params).then((response) => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const workTeamIds = row.workTeamId || this.ids;
      this.$confirm(
        '是否确认作业班组"' + (row.workTeamName || "已勾选") + '"的班组?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delTeam(workTeamIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有作业班组数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportTeam(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    /** 新增考勤时段 */
    addTeamSpan() {
      this.form.teamSpanList.push({
        teamSpanName: null,
        workTime: null,
        personId: null,
        fenceId: null,
      });
    },
    deleteTeamSpan(index) {
      this.form.teamSpanList.splice(index, 1);
    },
  },
};
</script>
